import React, { Component } from 'react';
import {
  Card,
  Button,
  Table,
  Menu,
  Input,
  Divider,
  Popconfirm,
  Modal,
  message
} from 'antd';
import { connect } from 'dva';
import SupplierItem from './components/Supplier';
import config from '../../../config/web.config'
import styles from './index.less';
import { getValueWithLocalStorage, getOwner } from '@/utils/authority';

const namespace = 'Inventory';

const mapStateToProps = state => {
  const list = state[namespace].supplierList;
  const isLoading = state[namespace].supplierLoading;
  return {
    list,
    isLoading,
  };
};

const mapDispatchToProps = dispatch => {
  return {
    getList: () => {
      const action = {
        type: `${namespace}/querySupplier`,
        payload: {
          owner: getOwner(),
        },
      };
      dispatch(action);
    },
    saveItem: (values) => {
      const action = {
        type: `${namespace}/saveSupplier`,
        payload: {
          ...values,
          owner: getOwner(),
        },
      };
      return dispatch(action);
    },
    editItem: (values) => {
      const action = {
        type: `${namespace}/editSupplier`,
        payload: {
          ...values,
        },
      };
      return dispatch(action);
    },    
    delItem: (_id) => {
      const action = {
        type: `${namespace}/delSupplier`,
        payload: {
          id: _id,
        },
      };
      return dispatch(action);
    },
  };
};

@connect(
  mapStateToProps,
  mapDispatchToProps
)
export default class ContactList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      itemData: {},
      modalLoading: false,
    };
    // this.formRef = React.createRef();
  }

  componentDidMount() {
    config.loadlCNZZ()
    this.reloadData();
  }

  reloadData = () => {
    this.props.getList();
  };

  // 新建
  handleCreateItem = (event) => {
    event.preventDefault();
    this.setState({
      modalVisible: true,
      itemData: { }
    });
  }

  // 编辑
  handleEditItem = (record, event) => {
    event.preventDefault();
    this.setState({
      modalVisible: true,
      itemData: record
    });
  }

  handleDelItem = (id) => {
    const { delItem, saveItem, getList } = this.props;
    delItem(id).then(res => {
      if(res.code === 1){
        message.success("删除供应商成功");
        getList()
      }else{
        message.error( res.msg || "删除供应商失败");
      }
    });
  }

  handleModalOk = () => {
    this.formInstance.handleSubmit();
  }

  handleModalCancel = () => {
    this.setState({
      modalVisible: false,
    });
  }

  handleSaveForm = (values) => {
    const { editItem, saveItem, getList } = this.props;
    this.setState({
      modalLoading: true
    });
    if(values.id){
      editItem(values).then(res => {
        if(res.code === 1){
          message.success("编辑供应商成功");
          this.setState({
            modalVisible: false,
            modalLoading: false,
            itemData: {}
          }, getList);
        }else{
          message.error( res.msg || "编辑供应商失败");
          this.setState({
            modalLoading: false,
          });
        }
      })
    }else{
      saveItem(values).then(res => {
        if(res.code === 1){
          message.success("新增供应商成功");
          this.setState({
            modalVisible: false,
            modalLoading: false,
            itemData: {}
          }, getList);
        }else{
          message.error( res.msg || "新增供应商失败");
          this.setState({
            modalLoading: false,
          });
        }
      })
    }
  }

  saveInstance = (instance) => {
    this.formInstance = instance;
  }

  render() {
    const columns = [
      {
        title: '供应商',
        dataIndex: 'suppliercompanyname',
        key: 'suppliercompanyname',
      },
      {
        title: '联系人',
        dataIndex: 'managername',
        key: 'managername',
        width: 150,
      },
      {
        title: '手机号',
        dataIndex: 'tel',
        key: 'tel',
        width: 150,
      },
      {
        title: '地址',
        dataIndex: 'address',
        key: 'address',
        width: 150,
      },
      {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
        width: 150,
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        width: 120,
        render: (text, record) => (
          <span>
            <a href="#" onClick={(event)=>this.handleEditItem(record, event)}>编辑</a>
            <Divider type="vertical" />
            <Popconfirm
                  title="确认删除此供应商?"
                  onConfirm={ () => this.handleDelItem(record._id) }
                  okText="确认"
                  cancelText="取消"
                >
              <a href="#" className={styles.delBtnStyle}>
                删除
              </a>
            </Popconfirm>
          </span>
        ),
      },
    ];

    const { modalVisible, modalLoading, owner, itemData } = this.state;
    const { isLoading, list } = this.props;

    const extraContent = (
      <div className={styles.extraContent}>
        <Button type="primary"
          onClick={this.handleCreateItem}
        >新增</Button>
      </div>
    );

    return (
      <Card
        bordered={false}
        title={'供应商管理'}
        style={{ marginTop: 24 }}
        bodyStyle={{ padding: '1px 0px 0px 0px' }}
        extra={extraContent}
      >
        <Table
          columns={columns}
          loading={isLoading}
          dataSource={list}
          rowKey="_id"
          pagination={false}
        />

        <Modal 
          title={ itemData._id ? "编辑供应商" : "新建供应商" }
          width={600}
          visible={modalVisible}
          confirmLoading={modalLoading}
          onOk={this.handleModalOk}
          onCancel={this.handleModalCancel}
        >
          <SupplierItem 
            saveInstance = {this.saveInstance}
            onSaveForm = {this.handleSaveForm}
            // ref={this.formRef}
            data={itemData}
          />
        </Modal>
      </Card>
    );
  }
}